# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import api, fields, models, _


class MrpProduction(models.Model):
    _inherit = 'mrp.production'

    @api.constrains('move_raw_ids')
    def _constrains_move_raw_ids(self):
        for production in self:
            sale_id = production.s_sale_order_line_ids.order_id or production._get_sources().s_sale_order_line_ids.order_id
            if sale_id and sale_id.meterial_id:
                order_meterial_lines = sale_id.meterial_id.line_ids
                for line in production.move_raw_ids.filtered(lambda x: not x.origin_product_id):
                    real_line = order_meterial_lines.filtered(lambda x: x.product_id == line.product_id)
                    if real_line and real_line.real_product:
                        line.write({
                            'origin_product_id': line.product_id.id,
                            'product_id': real_line.real_product.id,
                            'panel_need_qty': line.panel_need_qty * real_line.convertible_ratio,
                            'product_uom_qty': line.product_uom_qty * real_line.convertible_ratio,
                            'convertible_ratio': real_line.convertible_ratio,
                        })

class PlanMaterialWizard(models.TransientModel):
    _inherit = 'plan.material.requirement.wizard'

    def action_plan_material_requirement(self):
        res = super().action_plan_material_requirement()
        # 计算替代物料
        productions = self.sale_order_line_ids.s_mrp_production_ids
        all_products = productions
        for production in productions:
            all_products |= production._get_all_child()
        all_products._constrains_move_raw_ids()
        return res